//
//  OrderCheckViewController.m
//  随便点
//
//  Created by ZC on 15/3/31.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "OrderCheckViewController.h"
#import "oneCheckView.h"
#import "DropDown2.h"
#import "AppDelegate.h"
#import "orderViewController.h"
#import "psztViewController.h"
#import "balancePaymentViewController.h"
#define Kddxqing @"http://www.51anys.com:8080/waimaiwang/order/details"
#define Ktjdd @"http://www.51anys.com:8080/waimaiwang/order/confirm"

@interface OrderCheckViewController (){

    oneCheckView *oneView ;
    int Y;
    AppDelegate *del;
    NSDictionary *dic;
    NSString *str;
    NSString *Kxianshi;
    
    NSDictionary *xqdic;
    NSMutableArray *GoodsList;
    NSDictionary *Order;
    NSDictionary *tijiaodic;
    NSString *moren;
    NSString *zffs;
    UIAlertView *_alert;
    NSString *dingdid;
}

@end

@implementation OrderCheckViewController

- (void)viewDidLoad {
    del=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;

    GoodsList = [NSMutableArray array];
    //加载自定义的scrollview
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"oneCheckView" owner:self options:nil];
    oneView = nib[0];
    
    //框架scrollview的大小
    self.CheckScrollView.contentSize = CGSizeMake(self.view.frame.size.width, oneView.frame.size.height);
    
    //把自定义的scrollview添加到框架scrollview上
    [self.CheckScrollView addSubview:oneView];
    
    //起始高度
    Y = 5;
    
    [self ddxq];
    
    //加载第二个view上的“支付方式”
    [self loadSecondView];
    
    [self loading];
    
    [oneView.payButton addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [super viewDidLoad];
    
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
    
    del.detailsVC.array=[NSMutableArray array];
    
}

-(void)action{
    if (del.anniu == nil||[del.anniu isEqual:@""]) {
        zffs = moren;
    }else{
        zffs = del.anniu;
    }
    
    NSString *dingdid;
    if (del.querId == nil||[del.querId isEqualToString:@""]) {
        dingdid = del.xhlddid;
    }else{
        dingdid = del.querId;
    }
    NSURL *url=[NSURL URLWithString:Ktjdd];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"orderId=%@&addressId=%@&mark=%@&requireTime=%@&payType=%@",dingdid,del._dizhiID,oneView.beizhu.text,oneView.timeLabel.text,zffs];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        tijiaodic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:tijiaodic waitUntilDone:YES];
        if ([zffs isEqual:@"货到付款"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            _alert = alert;
            [alert show];
        }else if([zffs isEqual:@"建设网银支付"]){
            del.pd = @"建设网银";
            psztViewController *zt = [self.storyboard instantiateViewControllerWithIdentifier:@"psztVC"];
            [self.navigationController pushViewController:zt animated:YES];
        }else if ([zffs isEqual:@"支付宝付款"]){
            del.pd = @"支付宝";
            psztViewController *zt = [self.storyboard instantiateViewControllerWithIdentifier:@"psztVC"];
            [self.navigationController pushViewController:zt animated:YES];
        }else{
            balancePaymentViewController *bp = [self.storyboard instantiateViewControllerWithIdentifier:@"balancePaymentVC"];
            [self.navigationController pushViewController:bp animated:YES];
        }
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        orderViewController *order = [self.storyboard instantiateViewControllerWithIdentifier:@"orderviewCV"];
        [self.navigationController pushViewController:order animated:YES];
    }
}
-(void)ddxq{
    if (del.querId == nil||[del.querId isEqualToString:@""]) {
        dingdid = del.xhlddid;
    }else{
        dingdid = del.querId;
    }
    NSURL *url=[NSURL URLWithString:Kddxqing];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"orderId=%@",dingdid];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        xqdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:xqdic waitUntilDone:YES];
        GoodsList = xqdic[@"goodsList"];
        Order = xqdic[@"order"];
        [self cai];
    }];
}
-(void)loading{
    str = @"http://www.51anys.com:8080/waimaiwang/user/getDefault/";
    Kxianshi = [NSString stringWithFormat:@"%@%@",str,del._id];
    NSURL *url=[NSURL URLWithString:Kxianshi];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:dic waitUntilDone:YES];
        oneView.Label12.text= [NSString stringWithFormat:@"%@",dic[@"userId"]];
        oneView.Label2.text = [NSString stringWithFormat:@"%@",dic[@"mobile"]];
        oneView.Label3.text = [NSString stringWithFormat:@"%@",dic[@"streetName"]];
        del._dizhiID = [NSString stringWithFormat:@"%@",dic[@"id"]];
    }];
}
-(void)refreshData:(NSArray *)sender{
}
-(void)cai{
    //菜名数组
    NSMutableArray *array=[NSMutableArray array];
    NSMutableArray *array1=[NSMutableArray array];
    NSMutableArray *array2=[NSMutableArray array];
            for (NSDictionary *smallarray in GoodsList) {
                
            if (![smallarray[@"count"]  isEqual: @"0"]) {
                [array addObject: smallarray[@"goodsName"]];
                [array1 addObject: smallarray[@"count"]];
                [array2 addObject: smallarray[@"price"]];
            }
        }
        DropDown2 *dd1 = [[DropDown2 alloc] init];
    if (dingdid == del.xhlddid) {
        oneView.timeLabel.text = @"";
    }else{
        oneView.timeLabel.text = [NSString stringWithFormat:@"%@",Order[@"requireTime"]];
    }
        oneView.totalCount.text = [NSString stringWithFormat:@"%@",Order[@"count"]];
        oneView.totalPrice.text = [NSString stringWithFormat:@"%@",Order[@"sum"]];
        oneView.distributionMoney.text = [NSString stringWithFormat:@"%@",Order[@"sendCost"]];
         if (dingdid == del.xhlddid){
    oneView.beizhu.text = @"";
}else{
    oneView.beizhu.text = [NSString stringWithFormat:@"%@",Order[@"mark"]];
}
        dd1.textField.text = [NSString stringWithFormat:@"%@",Order[@"type"]];
    
    // 加载第一个view上的订单信息
    [self loadDishes:array Price:array1 Number:array2];
}

-(void)loadDishes:(NSMutableArray *)dishesArray Price:(NSMutableArray *)priceArray Number:(NSMutableArray *)numberArray{
    for (int j=0; j<dishesArray.count; j++) {
        
        [oneView SetupDishesName:dishesArray[j] Price:priceArray[j] Number:numberArray[j] SetY:Y];
        
        //每添加一行，Y值就 ＋20
        Y+=20;
    }
    //第一个view的高度在原来的基础上 ＋10 成为最新高度
    oneView.FirstView.frame = CGRectMake(0, oneView.FirstView.frame.origin.y, self.view.frame.size.width, Y + 10 );
    
    //第二个view的 Y 值在原来的基础上 ＋ 第一个view的最新高度
    oneView.SecondView.frame = CGRectMake(0, oneView.FirstView.frame.origin.y + Y +10, self.view.frame.size.width, oneView.SecondView.frame.size.height);
    
    //整个scrollview的高度，在原有的高度上 ＋ 第一个view的最新高度
    self.CheckScrollView.contentSize = CGSizeMake(self.view.frame.size.width, oneView.frame.size.height + Y +10);
}


-(void)loadSecondView{
    DropDown2 *dd1 = [[DropDown2 alloc] initWithFrame:CGRectMake(10, 160, 355, 30)];
    NSArray *arr=[[NSArray alloc]initWithObjects:@"货到付款",@"余额付款",@"支付宝付款",@"建设网银支付",nil];
    dd1.tableArray = arr;
    dd1.textField.text =[arr objectAtIndex:0];
    moren = dd1.textField.text;
    
    [oneView.SecondView addSubview:dd1];
    oneView.totalCount.text=del.BuyCount;
    oneView.totalPrice.text=del.BuyPrice;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [oneView.beizhu resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
